<template>
	<div class="content">
		<div class="content-top">
			潜客管理_合同详情
		</div>
		<div class="car-title">
			<div class="car-title-left">基本信息</div>
		</div>
		<div class="car-detail">
			<el-row>
				<el-col :span="8">合同编号：{{detail.contractCode}}</el-col>
				<el-col :span="8">购车车主：{{detail.vehicleOwnerChineseName}}</el-col>
				<el-col :span="8">联系号码：{{detail.vehicleOwnerPhone}}</el-col>
			</el-row>
            <el-row>
				<el-col :span="8">证件类型：{{detail.vehicleOwnerIdTypeValue}}</el-col>
				<el-col :span="8">证件号码：{{detail.vehicleOwnerIdNumber}}</el-col>
				<el-col :span="8">订单号码：{{detail.orderNumber}}</el-col>
			</el-row>
            <el-row>
                <el-col :span="8">定金：{{priceFixed(detail.downPayment)}}</el-col>
				<el-col :span="8">车辆总价：{{priceFixed(detail.vehicleTotalPrice)}}</el-col>
				<el-col :span="8">商业折扣：{{priceFixed(detail.vehicleCommercialDiscount)}}</el-col>
			</el-row>
            <el-row>
                <el-col :span="8">国家补贴：{{priceFixed(detail.vehicleStateSubsidies)}}</el-col>
				<el-col :span="8">地方补贴：{{priceFixed(detail.vehicleLocalSubsidies)}}</el-col>
				<el-col :span="8">实际购车总价：{{priceFixed(detail.vehicleActualTotalPrice)}}</el-col>
			</el-row>
            <el-row>
                <el-col :span="8">协议签署日：{{detail.dateOfAgreement}}</el-col>
				<el-col :span="8">车辆类型：{{detail.vehicleModel}}</el-col>
				<el-col :span="8">业务员姓名：{{detail.sysUserChineseName}}</el-col>
			</el-row>
			<el-row>
                <el-col :span="8">合同状态：{{textConversion(detail.processStatus)}}</el-col>
			</el-row>
		</div>
        <div class="car-title">
			<div class="car-title-left">合同流程</div>
		</div>
		<div class="car-table-page">
        <div class="car-detail-table">
			<el-table :data="recordList" show-header stripe style="width: 100%;">
				<el-table-column align="center" width="300" label="合同编号">
					<template slot-scope="scope">{{scope.row.contractId}}</template>
				</el-table-column>
				<el-table-column align="center" label="状态">
					<template slot-scope="scope">{{scope.row.contractVerificationStatusValue}}</template>
				</el-table-column>
				<el-table-column align="center" label="操作人">
					<template slot-scope="scope">{{scope.row.operatorName}}</template>
				</el-table-column>
				<el-table-column align="center" label="操作类型">
					<template slot-scope="scope">{{scope.row.approvalProcessValue}}</template>
				</el-table-column>
				<el-table-column align="center" label="操作时间">
					<template slot-scope="scope">{{scope.row.createDate}}</template>
				</el-table-column>
			</el-table>
		</div>
            <div class="content-page">
				<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="page"
				:page-size=limit layout="prev, pager, next, jumper" :total=total>
				</el-pagination>
			</div>
		</div>
        <div class="car-title center-button">
            <center>
				<el-button type="primary" v-if="buttonType.showReviewButtonStatus" @click="examine">审核</el-button>
				<el-button type="primary" v-if="buttonType.showApprovalButtonStatus" @click="approval">审批</el-button>
				<el-button type="primary" v-if="userId == detail.sysUserId && buttonType.submitReviewButtonStatus" @click="submit(3)">提交</el-button>
                <el-button type="primary" @click="previewContract" class="el-icon-view" v-if="buttonType.exportButtonStatus">预览合同</el-button>
				<el-button type="primary" icon="el-icon-download" @click="exportContract" v-if="buttonType.exportButtonStatus">导出合同</el-button>
				<el-button type="primary" @click="onBack">返回</el-button>
			</center>
		</div>
        <div class="car-detail application-reason" v-if="detail.processStatus != 50">
			<label for="">备注： </label>
			<el-input v-model="reason" :rows="8" style="width:88%" type="textarea" placeholder="请输入备注"></el-input>
		</div>
		<div class="car-title center-button" v-if="buttonType.turnDownButtonStatus">
			<center v-show="to_examine">
				<el-button type="primary" @click="submit(1)">审核通过</el-button>
				<el-button type="primary" @click="submit(4)">驳回</el-button>
			</center>
			<center v-show="to_approval">
				<el-button type="primary" @click="submit(2)">审批通过</el-button>
				<el-button type="primary" @click="submit(5)">驳回</el-button>
			</center>
		</div>
		
	</div>
</template>

<script>
	export default{
		props:['id'],
		components:{
		
		},
		data(){
			return{
			   detail:'',
			   reason:'',
			   total:1,
			   page:1,
			   limit:5,
			   recordList:[],
			   buttonType:[],
			   to_examine:false,
			   to_approval:false,
			   userId:localStorage.getItem('id'),
			   state:[ {id:0,name:'待提交'},
					{id:1,name:'审核中'},
					{id:50,name:'审批通过'},
					{id:99,name:'驳回'},]

			}
			
		},
		created() {
		},
		mounted() {
			this.getContractDetail()
			this.getContractRecord()
		},
		methods:{
			priceFixed(price){
				if(price){return price.toFixed(2)}
			},
			examine(){
				this.to_examine = true
				this.to_approval = false
			},
			approval(){
				this.to_examine = false
				this.to_approval = true
				console.log(1111)
			},
            getContractDetail(){
                var self = this
                this.$axios.get(this.$global.serverIp + 'crm/crmpurchasecontract/detail/' + self.id)
                .then(res =>{
					  self.detail = res.data.purchaseContract
					  self.buttonType = res.data
					  
                })
            },
			textConversion(idx){
				for(let item of this.state){
					if(item.id == idx){
                      return item.name
					}
				}
			},
			/* 审批、审核、提交、驳回 */
			submit(type){
				var url = ''
				if( type == 4 && this.to_examine == true){
                   url = 'crm/crmpurchasecontract/turn-down-contract'
				}else if(type == 5 && this.to_approval == true){
                   url = 'crm/crmpurchasecontract/turn-down-contract-general-manager'
				}else if( type == 2 ){
					url = 'crm/crmpurchasecontract/approve-contract'
				}else if( type == 1){
					url = 'crm/crmpurchasecontract/review-contract'
				}else{
					url = 'crm/crmpurchasecontract/submit-contract'
				}
				this.$confirm('是否继续该操作', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
                    var self = this
					this.$axios.post(this.$global.serverIp + url ,{
						"contractId":self.id,
						"approvalFeedback":self.reason
					})
					.then(res =>{
                         if(res != ''){
						   self.$popup.open('提交成功')
						   this.$emit('contractDetail',2)
						 }
					})
				})
				
			},
			/* 预览合同 */
			previewContract(){
				var self = this
				this.$axios.get(this.$global.serverIp + 'crm/crmpurchasecontract/preview-purchase-contract-pdf?id='+self.id, {
						responseType: 'blob' //告诉服务器我们需要的响应格式
					})
					.then(res => {
						let blob = new Blob([res.data], {
							type: 'application/pdf' //将会被放入到blob中的数组内容的MIME类型 
						});
						let objectUrl = URL.createObjectURL(blob); //生成一个url
						window.open(objectUrl)
						window.URL.revokeObjectURL(objectUrl);
					})
					.catch(err => {
						console.log(err);
					})
			},
			/* 导出 */
			exportContract(){
				var self = this
				const loading = this.$loading({
					lock: true,
					text: '拼命下载中...',
					target: document.querySelector('.content')//设置加载动画区域
				});
				fetch(this.$global.serverIp + 'crm/crmpurchasecontract/export-purchase-contract-pdf?id='+ self.id,{
						responseType: 'blob',//告诉服务器我们需要的响应格式
						method:'post',
						headers:{
							"Content-type": "application/x-www-form-urlencoded",
							"Authorization": 'Bearer '+localStorage.getItem('token')
					    }
				})
				.then(function(response) { 
					if (response.ok) {       
							return response.arrayBuffer();
					
					}    
					throw new Error('Network response was not ok.');
				}).then(function(arraybuffer) {    
					loading.close();
					let blob = new Blob([arraybuffer], { type: `application/pdf;charset-UTF-8` //word文档为msword,pdf文档为pdf
					});    
					let objectURL = URL.createObjectURL(blob);    
					let downEle = document.createElement("a"); 
					let fname = self.detail.vehicleOwnerChineseName+ ' ' + new Date().toLocaleDateString() //下载文件的名字
					downEle.href = objectURL;
					downEle.setAttribute("download", fname);    
					document.body.appendChild(downEle);
					downEle.click();
					window.URL.revokeObjectURL(objectURL)
				}).catch(function(error) {    
					console.log('There has been a problem with your fetch operation: ', error);
				});

			},
		
			/* 合同审批记录 */
			getContractRecord(){
				var self = this
                this.$axios.post(this.$global.serverIp + 'crm/crmcontractapprove/findAllOrPage',{
					"page":self.page,
					"limit":self.limit,
					"contractId":self.id,
					"paginationFlag": true
				})
                .then(res =>{
					  self.recordList = res.data.list
					  self.total = res.data.totalCount
                })
			},
			
			
			handleSizeChange(val) {
			
			},
			handleCurrentChange(val) {
				this.page = val;
				this.getContractRecord()
            },
            onBack(){
                this.$emit('contractDetail')
			},
			
         
		}
	}
</script>

<style>
	.car-title {
		margin: 26px 0px 0px 30px;
		overflow: hidden;
		font-size: 16px;
        width: 1088px;
	}
	
	.car-title-left {
		float: left;
		color: #606B82;
		margin-bottom: 16px;
	}
	
	.car-title-right {
		float: right;
		color: #FD943F;
		margin-bottom: 10px;
	}
	
	.car-title-right:hover {
		cursor: pointer;
		opacity: 0.3;
	}
	
	.car-detail {
		width: 1088px;
		height: auto;
		background-color: #F2F6FA;
		border: 1px solid #C9CDD1;
		padding-left: 30px;
		box-sizing: border-box;
		margin-left: 30px;
		padding-top: 40px;
	}
	.car-detail-table{
		width: 1088px;
		height: 300px;
		overflow: auto;
		background-color: #F2F6FA;
		border: 1px solid #C9CDD1;
		margin-left: 30px;
	}
	.car-table-page{
		width: 1088px;
		height: 300px;
	}
	.car-detail .el-row {
		margin-bottom: 30px;
		font-size: 14px;
		color: #2D384C;
	}
	.application-reason{
		display: flex;
		align-items: flex-start;
	}
	.center-button{
		padding-bottom: 30px;
	}
</style>

